﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CLEXA.AdminClient.ViewModel
{
    internal sealed class UserChangePasswordVM : VMBase
    {
        private readonly IFacade facade;
        private readonly int userId;
        private readonly string username;
        private string newPassword;
        private ICommand ok;
        private ICommand cancel;

        public int UserId
        {
            get { return userId; }
        }

        public string Username
        {
            get { return username; }
        }

        public string NewPassword
        {
            get { return newPassword; }
            set
            {
                if (newPassword != value)
                {
                    newPassword = value;
                    RaisePropertyChanged("NewPassword");
                }
            }
        }

        public ICommand OK
        {
            get 
            {
                if (ok == null)
                {
                    ok = new RelayCommand(DoOK, CanOK);
                }
                return ok; 
            }
        }

        public ICommand Cancel
        {
            get
            {
                if (cancel == null)
                {
                    cancel = new RelayCommand(DoCancel);
                }
                return cancel;
            }
        }

        public UserChangePasswordVM(IFacade facade, int userId)
        {
            this.facade = facade;
            this.userId = userId;
            this.username = facade.Users[userId].Username;
        }

        private void DoOK()
        {
            try
            {
                facade.UserChangePassword(userId, newPassword);
            }
            catch (Exception ex)
            {
                facade.ShowErrorDialog("An unexpected error occured while saving the user.", ex);
                return;
            }
            facade.CloseWindow(this);
        }

        private bool CanOK()
        {
            return !string.IsNullOrEmpty(newPassword);
        }

        private void DoCancel()
        {
            facade.CloseWindow(this);
        }
    }
}
